<template>
  <div class="pending">
    <div class="formSearch">
      <el-form
        :inline="true"
        :model="query"
      >
        <el-form-item label="上次消费时间">
          <div class="dateBox">
            <el-form-item>
              <el-date-picker
                v-model="query.lastTimes"
                type="datetimerange"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                value-format="YYYY-MM-DD HH:mm:ss"
              />
            </el-form-item>
          </div>
        </el-form-item>
        <el-form-item label="成为客户时间">
          <div class="dateBox">
            <el-form-item>
              <el-date-picker
                v-model="query.dates"
                type="datetimerange"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                value-format="YYYY-MM-DD HH:mm:ss"
              />
            </el-form-item>
          </div>
        </el-form-item>
        <el-form-item class="inputWide" label="手机号">
          <el-input
            v-model="query.phone"
            maxlength="11"
            placeholder="请输入内容"
          />
        </el-form-item>
        <el-form-item class="inputWide" label="客户标签">
          <el-select
            v-model="query.labelId"
            placeholder="客户标签"
            clearable
          >
            <el-option
              v-for="item in tagList"
              :key="item.labelId"
              :label="item.labelName"
              :value="item.labelId"
            />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">查询</el-button>
          <el-button type="primary" @click="handleClear">重置</el-button>
          <!--          <el-button type="primary" @click="addTag">添加标签</el-button>-->
          <el-button type="primary" @click="handleCreate">添加客户</el-button>
          <el-button type="success" @click="userDataExport">导出</el-button>
        </el-form-item>
      </el-form>
    </div>
    <!-- 表格 -->
    <div class="tableBox">
      <el-table
        v-loading="tableLoading"
        :data="tableData"
        border
        :header-cell-style="{ background: '#EEF3FF', color: '#333333' }"
        tooltip-effect="dark"
        style="width: 100%"
        class="dataTable"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column prop="name" label="客户昵称" show-overflow-tooltip />
        <el-table-column prop="phone" label="手机号" show-overflow-tooltip />
        <el-table-column
          prop="frequency"
          label="消费次数"
          show-overflow-tooltip
        />
        <el-table-column
          prop="total"
          label="累计消费金额（元）"
          show-overflow-tooltip
        />
        <el-table-column
          prop="lastTime"
          label="上次消费时间"
          show-overflow-tooltip
        />
        <el-table-column
          prop="time"
          label="成为客户时间"
          show-overflow-tooltip
        />
        <el-table-column
          :formatter="(row) => (row.registerIp ? row.registerIp : '-')"
          label="注册IP"
          show-overflow-tooltip
        />
        <el-table-column
          :formatter="(row) => (row.lastLoginIp ? row.lastLoginIp : '-')"
          prop="time"
          label="最后登录IP"
          show-overflow-tooltip
        />
        <el-table-column
          prop="labelName"
          label="客户标签"
          show-overflow-tooltip
        />
        <el-table-column label="操作" show-overflow-tooltip fixed="right">
          <template #default="scope">
            <div class="btnList">
              <el-button type="primary" link @click="edit(scope.row)">加标签</el-button>
              <el-button
                type="primary"
                link
                @click="showDetail(scope.row.buyerUserId)"
              >详情</el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>
      <div class="fenye">
        <el-pagination
          :current-page="page.page"
          :page-sizes="[10, 20, 50, 100]"
          :page-size="page.pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          background
          :total="page.total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>
    <!-- 添加标签 -->
    <el-dialog
      v-model="visible.tag"
      :close-on-click-modal="false"
      title="添加标签"
      width="400px"
      top="50px"
      class="group-dialog"
    >
      <div class="changeCustomer">
        <el-form ref="ruleForm" label-width="50px">
          <el-form-item class="inputWide" label="标签">
            <el-select
              v-model="currentData.labelIds"
              multiple
              collapse-tags
              placeholder="请选择"
            >
              <el-option
                v-for="item in tagList"
                :key="item.labelId"
                :label="item.labelName"
                :value="item.labelId"
              />
            </el-select>
          </el-form-item>
        </el-form>
      </div>
      <template #footer>
        <el-button type="primary" @click="saveCustomerTag">保 存</el-button>
        <el-button @click="closeAddTag">取 消</el-button>
      </template>
    </el-dialog>

    <!-- 详情弹窗 -->
    <CustomerDetail ref="customerDetailRef" />
    <Form
      ref="formRef"
      :tag-list="tagList"
      @refresh="getAll"
    />
  </div>
</template>

<script setup>
import { defineComponent, onMounted, reactive, ref } from 'vue'

import CustomerDetail from '@/views/customer/customerList/customerDetail.vue'
import Form from './form.vue';
import {
  getCustomerList,
  getLabelData,
  addCustomer,
  deleteLabel,
  buyerSaveLabel,
  userExport,
} from '@/api/customer'

defineComponent({
  name: 'CustomerList'
})

let visible = reactive({
  user: false,
  tag: false,
})

let tagList = ref([]);
function getTagList () {
  getLabelData().then(res => {
    if (res.code === '') {
      tagList.value = res.data
    } else {
      ElMessage.error(res.message)
    }
  })
}

const tableLoading = ref(false)

let page = reactive({
  page: 1,
  pageSize: 10,
  total: 0
});

let query = reactive({
  labelId: null,
  labelName: '', // 标签名称
  dates: [], // 成为客户时间数组
  lastTimes: [], // 上次消费时间
  phone: '', // 手机号
});

let tableData = ref([]);

// 初始化查询所有数据
function getAll () {
  tableLoading.value = true
  getCustomerList(Object.assign(
    {},
    page,
    query,
  )).then(res => {
    tableData.value = res.data.list
    page.total = res.data.total
  }).finally(() => {
    tableLoading.value = false
  })
}
//  查询
function handleSearch () {
  page.page = 1
  getAll()
}
// 清除
function handleClear () {
  query.labelId = null
  query.labelName = ''
  query.dates = []
  query.lastTimes = []
  query.phone = ''
  page.page = 1
  getAll()
}
function handleSizeChange (val) {
  page.pageSize = val
  getAll()
}
function handleCurrentChange (val) {
  page.page = val
  getAll()
}

let currentData = reactive({
  buyerUserId: null,
  labelIds: []
})

/**
 * 添加客户
 */
let formRef = ref(null)
function handleCreate () {
  formRef.value.show()
}

/**
 * 客户详情
 */
let customerDetailRef = ref(null)
function showDetail (id) {
  customerDetailRef.value.show(id)
}
// 编辑
function edit (item) {
  currentData.labelIds = item.labelIds
  currentData.buyerUserId = item.buyerUserId
  visible.tag = true
}
function saveCustomerTag () {
  buyerSaveLabel({
    buyerUserId: currentData.buyerUserId,
    labelIds: currentData.labelIds,
  }).then((res) => {
    if (res.code === '') {
      ElMessage.success('添加成功')
      getAll()
      getTagList()
      visible.tag = false
    } else {
      ElMessage.error(res.message)
    }
  })
}
function closeAddTag () {
  visible.tag = false
  currentData.labelIds = []
}

// 导出用户
function userDataExport () {
  ElMessage({
    message: '数据导出中，请勿重复操作！',
    type: 'success',
  })
  userExport(Object.assign(
    {},
    page,
    query,
  )).then(res => {
    if (!res) {
      return
    }
    const blob = new Blob([res], { type: 'application/vnd.ms-excel' })
    const fileName = '用户列表.xls'
    if ('download' in document.createElement('a')) {
      // 非IE下载
      const elink = document.createElement('a')
      elink.download = fileName
      elink.href = URL.createObjectURL(blob)
      elink.style.display = 'none'
      document.body.appendChild(elink)
      elink.click()
      URL.revokeObjectURL(elink.href) // 释放URL 对象
      document.body.removeChild(elink)
    } else {
      // IE10+下载
      navigator.msSaveBlob(blob, fileName)
    }
  })
}

/**
 * ******************************************
 * ***************** 用户表单 ****************
 * ******************************************
 */
let userForm = ref({
  birthday: '',
  buyerUserId: '',
  ids: [],
  name: '',
  phone: '',
  remark: '',
  sex: '',
})
const userRules = {
  phone: [
    { required: true, message: '请输入客户手机号', trigger: 'blur' },
  ],
}
function saveCustomer (formEl) {
  if (!formEl) return
  formEl.validate((valid) => {
    if (valid) {
      const reg = /^[1][3,4,5,7,8,9][0-9]{9}$/
      if (!reg.test(userForm.value.phone)) {
        ElMessage.warning('请输入正确的手机号')
        return false
      }
      addCustomer(userForm.value).then((res) => {
        if (res.code === '') {
          ElMessage.success('添加成功')
          page.page = 1
          getAll()
          userForm.value = {}
          visible.user = false
        } else {
          ElMessage.error(res.message)
        }
      })
    }
  })
}
function closeAddCustomer () {
  visible.user = false
}

onMounted(() => {
  getAll()
  getTagList()
})
</script>

<style lang="scss" scoped>
.pending {
  padding: 20px;
  margin-top: 20px;
  background-color: #FFFFFF;
}
</style>